<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>

    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onColumnsChange="columns => this.columns = columns"

    >
    <template slot="controls" slot-scope="props">
      <el-popover placement="bottom">
        <el-button slot="reference" type="primary" size="small" style="margin-right:10px">月报导出</el-button>
        <el-date-picker
            @change="dateChenge"
            v-model="searchMonth"
            type="month"
            placeholder="选择月"
            value-format="yyyy-MM">
          </el-date-picker>
      </el-popover>


      <!-- <el-button class="hide_input" size="small" type="primary">月报导出
        <el-date-picker
          @change="dateChenge"
          v-model="searchMonth"
          type="month"
          placeholder="选择月"
          value-format="yyyy-MM">
        </el-date-picker>
      </el-button> -->
        <!-- <multiuse-button size="small" type="primary" :click="batchExamine.bind()" :disabled="disableds">打印旧件标签</multiuse-button> -->
        <multiuse-button size="small" type="primary" :loading="exportLoading" :click="exportData.bind()">导 出</multiuse-button>
      </template>
    </FilterTable>

    <BaseDialog
      :visible.sync="issearch"
      :title="'服务商查询'"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ownerSeacher  @close="dealercloseHandler" />
    </BaseDialog>
    <!-- <BaseDialog
      :visible.sync="visiblePeij"
      :title="'备件代码查询'"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <addPeij  @close="partcloseHandler" @selectArr="selectPeijFun" />
    </BaseDialog> -->
    <BaseDialog :visible.sync="visiblePeij" title="备件选择" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <addPeij :status="1" @selectArr="selectPeijFun" @closeVin="closeDialog"></addPeij>
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { stockQuery, getListForExport,exporturl,selectList } from '@/api/partsmanage/partinfos/partInfoManage/index';
import ownerSeacher from '@/pages/partsmanage/claim/approve/ownerSeacher';
import { exportExcelFile } from '@/utils/index';
import { notifyAction } from '@/utils';
import  addPeij  from '@/pages/partsmanage/partinfos/stockQuery/addPeij.vue';
import { isEmpty } from '@/utils/utils';
export default {
  name: "stockQuery",
  mixins: [dictionary],
  components: {ownerSeacher,addPeij},
  data() {
    return{
      searchMonth: null,
      exportLoading: false, // 导出加载中
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchApi: stockQuery,
      issearch: false, //服务商查询
      visiblePeij: false, //备件代码查询
      fetchParams: {xhrAbort: true}
    };
  },
  methods: {
    createTopFilterList() {
      return[
        {
          type: 'INPUT',
          label: '服务商代码',
          fieldName: 'dealerCode',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          },
          onInput: (val, data) => {
            this.changePrams(data);
          },
        },
        {
          type: 'INPUT',
          label: '服务商简称',
          fieldName: 'dealerName',
          readonly: true,
          disabled: true,
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '备件代码',
          fieldName: 'partNo',
          placeholder: '请输入',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun1()}></el-button>
              </div>
            );
          },
          onInput: (val, data) => {
            this.changePrams1(data);
          }
        },
        {
          type: 'INPUT',
          label: '备件名称',
          readonly: true,
          disabled: true,
          fieldName: 'partName',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '备件来源',
          fieldName: 'dataSources',
          placeholder: '请选择...',
          itemList: this.createDictList('1045',[10451003])
        },
        {
          type: 'SELECT',
          label: '账面数量大于0',
          fieldName: 'stockQuantity',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
      ]
    },
    createTableColumns () {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          align:"center",
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '服务商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          align:"center"
        },
        {
          title: '服务商简称',
          dataIndex: 'dealerShortName',
          sorter: true,
          align:"center"
        },
        {
          title: '备件代码',
          dataIndex: 'partNo',
          sorter: true,
          align:"center",
          width:"200"
        },
        {
          title: '备件名称',
          dataIndex: 'partName',
          sorter: true,
          align:"center",
          width:"200"
        },
        {
          title: '仓库代码',
          dataIndex: 'storageCode',
          sorter: true,
          align:"center"
        },
        {
          title: '仓库名称',
          dataIndex: 'storageName',
          sorter: true,
          align:"center"
        },
        {
          title: '账面数量',
          dataIndex: 'stockQuantity',
          sorter: true,
          align:"center"
        },
        {
          title: '预留数量',
          dataIndex: 'lockedQuantity',
          sorter: true,
          align:"center"
        },
        {
          title: '可用数量',
          dataIndex: 'usableStock',
          sorter: true,
          align:"center"
        },
        {
          title: '含税成本价',
          dataIndex: 'planPriceTaxed',
          sorter: true,
          precision: 2,
          align:"center",
          numberFormat: true
        },
        {
          title: '含税成本金额',
          dataIndex: 'stockPrice',
          sorter: true,
          precision: 2,
          align:"center",
          numberFormat: true
        },
        {
          title: '备件来源',
          dataIndex: 'dataSources',
          dictItems: this.createDictList('1045'),
          sorter: true
        },
      ]
    },

    closeDialog() {
      console.log('关闭');
      this.visiblePeij = false;
    },

    // 服务商简称 数据根据 code清空
    changePrams(val) {
      console.log('====服务商简称清除按钮生效====')
      if (!val) {
              // let result = 0;
              this.topFilterList.find(x => x.fieldName === 'dealerName').initialValue = '';
      }
    },
    // 备件名称 数据根据 code清空
    changePrams1(val) {
      console.log('====备件名称清除按钮生效====')
      if (!val) {
              // let result = 0;
              this.topFilterList.find(x => x.fieldName === 'partName').initialValue = '';
      }
    },

/*配件 */
async selectPeijFun(arr) {
      this.closeDialog();
      console.log('备件搜索框数据', arr[0] );


        /*表单选择*/
        console.log('表单');
        // this.fetchParams.partNo = arr[0].partNo;
        // this.fetchParams.partName = arr[0].partName;
        this.topFilterList.find((item) => item.fieldName == 'partNo').initialValue = arr[0].partNo;
        this.topFilterList.find((item) => item.fieldName == 'partName').initialValue = arr[0].partName;
        console.log('备件赋值后的查询条件',this.topFilterList);
        // this.formList.find((item) => item.fieldName == 'partSalesPrice').initialValue = arr[0].partSalesPrice;

        // let params = {};
        // params.addId = getAppId();
        // params.bjxmbh = arr[0].partNo;
        // this.rowDate.partNo = arr[0].partNo;

    },

    seacherFun(){
      this.issearch = true
    },
    seacherFun1(){
      this.visiblePeij = true
    },
    dealercloseHandler(val){
      if(val){
        this.topFilterList.find(x=>x.fieldName=='dealerCode').initialValue=val.dealerCode;
        this.topFilterList.find(x=>x.fieldName=='dealerName').initialValue=val.dealerShortname;
      }
      this.issearch=false;
    },
    partcloseHandler(val){
      if(val){
        this.topFilterList.find(x=>x.fieldName=='partNo').initialValue=val.partNo;
        this.topFilterList.find(x=>x.fieldName=='partName').initialValue=val.partName;
      }
      this.visiblePeij=false;
    },
    changeHandle(val) {
        console.log("=========此处校验查询必填参数=========");
        console.log(val);
        if((val.dealerCode == null || val.dealerCode == "") && (val.partNo == null || val.partNo == "")){

            return notifyAction('请输入服务商代码或备件代码!', 'warning');
        }
        this.fetchParams = Object.assign({}, val);
    },

    // //导出
    // exportData() {
    //   this.exportLoading = true;
    //   getListForExport(this.fetchParams).then(res => {
    //     exportExcelFile(res, '延保提醒导出');
    //   });
    //   this.exportLoading = false;
    // },

    // 导出
    // async exportData() {
    //   try {
    //     // let params = { reportNo: "RE202103060001" }
    //     let params = {...this.fetchParams}
    //     let res = await getListForExport(params);
    //     exportExcelFile(res.data, '店端库存查询')
    //   } catch (err) {
    //     console.warn(err)
    //   }
    // },
    async dateChenge(date) {
      // if (date == null) {
      //   return notifyAction('请选择月份!', 'warning');
      // }
      let tishiRes = await selectList({date:date});
      if (tishiRes.resultCode == 400) {return notifyAction('当前选择月份的报表数据还未更新，请选择上一个月的数据导出!', 'warning');}

      console.log(date)
      let json = Object.assign({}, { CODE: 'CODE_00000272' }, {date:date});
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
    },

    aotoAuditOrderSwitchChange(val,id){
      console.log("val===>"+val,id);
      this.$confirm('确认改变审单方式?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
      }).then(() =>{
        autoAuditOrderSwitchFuc({id:id,status:val == 10011001 ? 10011002: 10011001}).then(res =>{
          console.log(res);
          if(res.resultCode == 200 ){
            getList().then(res =>{
              if(res.resultCode == 200 ){
                  this.list = res.data.records
                      }
                    });
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          }else{
            this.$message({
              type: 'warning',
              message: res.errMsg || '操作失败!'
            });
            this.aotoAuditOrderSwitch = !val;
          }

        }).catch(err =>{
          this.$message({
            type: 'warning',
            message: err.errMsg || '操作失败!'
          });
          this.aotoAuditOrderSwitch = !val;
        })

      }).catch(err =>{
        this.$message({
          type: 'warning',
          message: '已取消!'
        });
        this.aotoAuditOrderSwitch = !val;
      })
    },


    // 导出
    exportData() {
  this.exportLoading = true;
  const obj = this.$refs.table.$refs.pageTable.sorterParams;
  const param = {
    ...this.fetchParams,
    dealerCode: this.topFilterList.find(x=>x.fieldName=='dealerCode').initialValue,
    partNo: this.topFilterList.find(x=>x.fieldName=='partNo').initialValue,
    sort: obj.sort,
    is_export: 1
  };
  getListForExport(param).then(response => {
    console.log("param" , param)
    if((param.dealerCode == null || param.dealerCode == "") && (param.partNo == null || param.partNo == "")){
      return notifyAction('请输入服务商代码或备件代码!', 'warning');
    }
    // if((this.topFilterList.find(x=>x.fieldName=='dealerCode').initialValue == null || this.topFilterList.find(x=>x.fieldName=='dealerCode').initialValue == "") && (this.topFilterList.find(x=>x.fieldName=='partNo').initialValue == null || this.topFilterList.find(x=>x.fieldName=='partNo').initialValue == "")){
    //   return notifyAction('导出时请先查询并输入服务商代码或备件代码!', 'warning');
    // }
    exportExcelFile(response.data, isEmpty(param.dealerCode) ? '店端库存查询 ' : param.dealerCode+' 店端库存查询 ');
    this.exportLoading = false;
  });
},

    collapseHandle() {
    },
  }
}
</script>
<style>
/*按钮日期选择器隐藏ipnut*/
.hide_input{
  position: relative !important;
}
.hide_input .el-date-editor {
  position: absolute ;
  top: 0 ;
  left: 0 ;
  opacity: 0;
}
.hide_input span .el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 50px;
}
</style>

